package com.example.smart_city_0829.activity.lawyer_consultation;

import static com.example.smart_city_0829.activity.lawyer_consultation.LawyerMainActivity.legalExpertiseList;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.smart_city_0829.R;
import com.example.smart_city_0829.activity.lawyer_consultation.fragment.CommentListFragment;
import com.example.smart_city_0829.activity.lawyer_consultation.fragment.LawyerInfoFragment;
import com.example.smart_city_0829.base.BaseActivity;
import com.example.smart_city_0829.base.CommonAdapter;
import com.example.smart_city_0829.entity.Base;
import com.example.smart_city_0829.entity.common.UploadResult;
import com.example.smart_city_0829.entity.lawyer_onsultation.LawyerList;
import com.example.smart_city_0829.entity.lawyer_onsultation.LegalExpertiseList;
import com.example.smart_city_0829.retrofit.NetCallBack;
import com.example.smart_city_0829.utils.Constant;
import com.example.smart_city_0829.view.MaxSizeGv;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;

public class ConsultationActivity extends BaseActivity {

    private CardView cardView;
    private ImageView userAvatar;
    private TextView nameTv;
    private TextView workYearsTv;
    private TextView goodAtTv;
    private TextView quesTimesTv;
    private TextView favorableRateTv;
    private Button quesType;
    private EditText quesDesc;
    private ImageView image;
    private EditText phoneEt;
    private Button postBt;


    private Integer LegalExpertiseId = null;
    private LawyerList.RowsBean lawyerData;

    private String uploadImgPath = null;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_consultation;
    }

    @Override
    protected void initView() {
        cardView = (CardView) findViewById(R.id.cardView);
        userAvatar = (ImageView) findViewById(R.id.user_avatar);
        nameTv = (TextView) findViewById(R.id.name_tv);
        workYearsTv = (TextView) findViewById(R.id.work_years_tv);
        goodAtTv = (TextView) findViewById(R.id.goodAt_tv);
        quesTimesTv = (TextView) findViewById(R.id.quesTimes_tv);
        favorableRateTv = (TextView) findViewById(R.id.favorableRate_tv);
        quesType = (Button) findViewById(R.id.ques_type);
        quesDesc = (EditText) findViewById(R.id.ques_desc);
        image = (ImageView) findViewById(R.id.image);
        phoneEt = (EditText) findViewById(R.id.phone_et);
        postBt = (Button) findViewById(R.id.post_bt);

    }

    @Override
    protected void initData() {
        lawyerData = (LawyerList.RowsBean) gson.fromJson(
                getIntent().getStringExtra("lawyerData"),
                new TypeToken<LawyerList.RowsBean>() {
                }.getType()
        );

        if (lawyerData != null) {
            Glide.with(context)
                    .load(Constant.BASE_URL + lawyerData.getAvatarUrl())
                    .into(userAvatar);

            nameTv.setText(String.valueOf(lawyerData.getName()));
            workYearsTv.setText("从业："+String.valueOf(Calendar.getInstance().get(Calendar.YEAR) - Integer.parseInt(lawyerData.getWorkStartAt().substring(0,4))) + "年");
            goodAtTv.setText("法律专长：" + lawyerData.getLegalExpertiseName());
            quesTimesTv.setText("咨询人数：" + lawyerData.getServiceTimes());
            favorableRateTv.setText("好评率：" + lawyerData.getFavorableRate() + "%");
        }
    }

    @Override
    protected void initEvent() {
        //选择问题类型
        quesType.setOnClickListener((v) -> {
            final MaxSizeGv maxSizeGv = new MaxSizeGv(context);
            maxSizeGv.setNumColumns(4);
            maxSizeGv.setAdapter(new LegalAdapter(Objects.requireNonNull(legalExpertiseList.getRows()), context));
            final AlertDialog dialog = new AlertDialog.Builder(context)
                    .setView(maxSizeGv)
                    .create();
            maxSizeGv.setOnItemClickListener((parent, view, position, id) -> {
                //TODO 休息一下
                final LegalExpertiseList.RowsBean item = (LegalExpertiseList.RowsBean) parent.getAdapter().getItem(position);
                LegalExpertiseId = item.getId();
                quesType.setText("已选择：" + item.getName());
                dialog.dismiss();
            });
            dialog.show();
        });

        image.setOnClickListener(v -> {
            if (hasStoragePermission()) {
                //Intent.ACTION_PICK 从数据中选择一个项目 (item)，将被选中的项目返回。
                //MediaStore.Images.Media.EXTERNAL_CONTENT_URI 获取外部的URI
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                //参数一:对应的数据的URI 参数二:使用该函数表示要查找文件的MIME类型
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, PERMISSION_REQUEST_PICTURE_CODE);

//                final Intent intent = new Intent();
//                intent.setType("image/*");
//                intent.setAction(Intent.ACTION_GET_CONTENT);
//                startActivityForResult(intent, PERMISSION_REQUEST_PICTURE_CODE);
            }
        });

        postBt.setOnClickListener(v -> {
            if (LegalExpertiseId == null) {
                showToastShort("暂未选择咨询类型");
                return;
            }

            final String content = quesDesc.getText().toString();
            if (TextUtils.isEmpty(content)) {
                showToastShort("未填写咨询问题");
                return;
            }

            if (TextUtils.isEmpty(uploadImgPath)){
                showToastShort("未上传图片");
                return;
            }

            final String phone = phoneEt.getText().toString();
            if (TextUtils.isEmpty(phone)) {
                showToastShort("未填写联系手机号");
                return;
            }

            final HashMap<String, Object> params = new HashMap<>();
            params.put("lawyerId", lawyerData.getId());
            params.put("legalExpertiseId", LegalExpertiseId);
            params.put("content", content);
            params.put("imageUrls",uploadImgPath);
            params.put("phone", phone);

            api.postConsultation(RequestBody.create(
                    gson.toJson(params),
                    MediaType.parse(Constant.MediaTypeParseJsonValue))
            ).enqueue(new NetCallBack<Base>() {
                @Override
                public void onResponse(Call<Base> call, Response<Base> response) {
                    if (response.body() == null) {
                        showToastShort("咨询失败，检查网络");
                    }

                    if (response.body().getCode() == 200) {
                        showToastShort("咨询成功，返回上一页");
                        ConsultationActivity.this.finish();
                    } else {
                        showToastShort("咨询失败");
                    }
                }
            });
        });
    }

    @Override
    protected String getActionBarTitle() {
        return "咨询律师";
    }

    @SuppressLint("Range")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PERMISSION_REQUEST_PICTURE_CODE && resultCode == RESULT_OK) {
            try {
                final String[] projection = {MediaStore.Images.Media.DATA};
                final Cursor cursor = getContentResolver().query(Objects.requireNonNull(data).getData(), projection, null, null, null);
                cursor.moveToFirst();
                final String path = cursor.getString(cursor.getColumnIndex(projection[0]));
                final Bitmap bitmap = BitmapFactory.decodeStream(
                        getContentResolver().openInputStream(Objects.requireNonNull(data).getData())
                );

                final RequestBody body = RequestBody.create(new File(path), MediaType.parse(Constant.MediaTypeParseImageValue));
                api.postFile(MultipartBody.Part.createFormData(
                        "file",
                        System.currentTimeMillis() + path.substring(path.lastIndexOf(File.separator) + 1), body)
                ).enqueue(new NetCallBack<UploadResult>() {
                    @Override
                    public void onResponse(Call<UploadResult> call, Response<UploadResult> response) {
                        if (response.body() == null) {
                            showToastShort("上传失败");
                            return;
                        }

                        uploadImgPath = response.body().getFileName();
                        showToastShort("上传成功");
                        image.setImageBitmap(bitmap);
                    }
                });

                cursor.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    private class LegalAdapter extends CommonAdapter<LegalExpertiseList.RowsBean, CommonAdapter.CommGridViewHolder> {

        public LegalAdapter(List<LegalExpertiseList.RowsBean> data, Context context) {
            super(data, context);
        }

        @Override
        protected void setData(LegalExpertiseList.RowsBean data, int position, CommGridViewHolder viewHolder, View convertView, Context context) {
            Glide.with(context)
                    .load(Constant.BASE_URL + data.getImgUrl())
                    .into(viewHolder.im);
            viewHolder.serverName.setText(data.getName());
        }

        @Override
        protected CommGridViewHolder getViewHolder() {
            return new CommGridViewHolder();
        }

        @Override
        protected void initView(CommGridViewHolder viewHolder, View convertView) {
            viewHolder.im = (ImageView) convertView.findViewById(R.id.im);
            viewHolder.serverName = (TextView) convertView.findViewById(R.id.server_name);
        }

        @Override
        protected int getItemLayoutResourceId() {
            return R.layout.server_list_item;
        }
    }
}